package sojupay

import (
	"context"

	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/logic/pay"
	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/pay/sojupay"
	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/types"
	"gitee.com/liuxuezhan/ar-platform/assets-api/pkg/consts"
	"gitee.com/liuxuezhan/ar-platform/assets-api/pkg/xerrors"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/assetsClient/rpc"
	"github.com/bytedance/sonic"
	"github.com/bytedance/sonic/decoder"
	"github.com/zeromicro/go-zero/core/logc"

	"github.com/zeromicro/go-zero/core/logx"
)

type PaymentNotifyLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// sojupay代收回调通知
func NewPaymentNotifyLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PaymentNotifyLogic {
	return &PaymentNotifyLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *PaymentNotifyLogic) PaymentNotify(req *types.SojuPaymentNotifyReq) (resp *types.SojuPaymentNotifyResp, err error) {
	// 回调信息转为 json 字符串
	b, _ := sonic.Marshal(req)
	logc.Info(l.ctx, string(b))
	// 获取 bcpay 配置信息
	conf, err := l.svcCtx.AssetsRpc.PayRecharge.RechargeChannelListByCode(l.ctx, &rpc.RechargeChannelByCodeRequest{Code: consts.SojupayCode})
	if err != nil {
		return nil, err
	}
	// 验签
	var data map[string]any
	dc := decoder.NewDecoder(string(b))
	dc.UseNumber()
	if err = dc.Decode(&data); err != nil {
		return nil, err
	}
	sign := sojupay.GenerateSign(data, conf.SecretKey)
	if sign != data["sign"] {
		logc.Error(l.ctx, "signature verification failed: ", sign, string(b))
		return nil, xerrors.ErrSignVerifyFailed
	}
	// 根据订单状态处理业务逻辑
	switch req.Status {
	case 2:
		_, err = l.svcCtx.AssetsRpc.PayRecharge.RechargeSuccess(l.ctx, &rpc.NotifyOKRequest{OrderNo: req.PaymentClId, ReturnJson: string(b)})
		if err != nil {
			logc.Error(l.ctx, err, string(b))
			return
		}
		pay.NewHandleOrderLogic(l.ctx, l.svcCtx).AddNotifitionMessage(&pay.NotifyMessageInfo{OrderNo: req.PaymentClId})

		resp = &types.SojuPaymentNotifyResp{
			ErrorCode: "0000",
		}
	case 3, 4:
		_, err = l.svcCtx.AssetsRpc.PayRecharge.RechargeFail(l.ctx, &rpc.NotifyFailRequest{OrderNo: req.PaymentClId, ReturnJson: string(b)})
		if err != nil {
			logc.Error(l.ctx, err, string(b))
			return
		}
		resp = &types.SojuPaymentNotifyResp{
			ErrorCode: "0000",
		}
	}
	return
}
